<?php

namespace app\mall\controller\admin;

use app\mall\model\MallCateAttr;
use app\mall\model\MallGoods as MallGoodsModel;
use app\mall\model\MallGoodsStock;
use FormBuilder\Driver\CustomComponent;
use FormBuilder\Factory\Elm;
use suframe\form\Form;
use think\db\exception\DataNotFoundException;
use think\facade\Db;
use think\facade\View;

/**
 * 公共商品配置
 */
class MallGoodsSetting extends Base
{
    protected $urlPre = '/mall/admin/mallGoodsSetting/';

    protected $goods_id;

    protected function setNav($active = null)
    {
        if ($this->request->isAjax()) {
            return false;
        }
        parent::setNav();
        $this->goods_id = $this->request->get('id');
        $navs = [
            'index' => ['商品总览', $this->urlABuild('index', ['id' => $this->goods_id])],
            'sku' => ['SKU', $this->urlABuild('sku', ['id' => $this->goods_id])],
            'images' => ['图集', $this->urlABuild('images', ['id' => $this->goods_id])],
        ];
        $active = $active ?: ($this->request->route()['method'] ?? 'index');
        $this->setAdminNavs($navs, $active);
    }

    /**
     * @var MallGoodsModel
     */
    protected $mallGoods;

    /**
     * @throws DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function initialize()
    {
        parent::initialize();
        $id = $this->request->get('id');
        $this->mallGoods = MallGoodsModel::find($id);
        if (!$this->mallGoods) {
            throw new DataNotFoundException("商品不存在");
        }
    }

    public function index()
    {
        $this->setNav();
        return View::fetch('/mallGoodsSetting/index');
    }

    /**
     * sku
     * @throws \Exception
     */
    public function sku()
    {
        if ($this->request->post()) {
            $cate_id = $this->mallGoods->cate_id;
            $sku = $this->request->post('sku');
            $rs = false;
            $ids = [];
            Db::startTrans();
            try {
                //更新sku
                $totalStock = 0;
                $miniPrice = 0;
                $miniPriceOrigin = 0;
                foreach ($sku['childProductArray'] as $item) {
                    $post = [
                        'cate_id' => $cate_id,
                        'goods_id' => $this->mallGoods->id,
                        'enable' => $item['enable'],
                        'product_no' => $item['product_no'],
                        'spec' => $item['spec'],
                        'stock' => $item['stock'],
                        'price' => $item['price'],
                        'price_origin' => $item['price_origin'],
                    ];
                    $obj = MallGoodsStock::where('goods_id', $this->mallGoods->id)
                        ->where('product_no', $item['product_no'])->find();
                    if (!$obj) {
                        $obj = new MallGoodsStock();
                    }
                    $rs = $obj->save($post) || $rs;
                    $ids[] = $obj->id;
                    //商品信息库存和价格计算
                    $totalStock += $item['stock'];
                    if ($item['price'] > 0) {
                        if ($miniPrice == 0) {
                            $miniPrice = $item['price'];
                        } elseif ($item['price'] < $miniPrice) {
                            $miniPrice = $item['price'];
                        }
                    }
                    if ($item['price_origin'] > 0) {
                        if ($miniPriceOrigin == 0) {
                            $miniPriceOrigin = $item['price_origin'];
                        } elseif ($item['price_origin'] < $miniPriceOrigin) {
                            $miniPriceOrigin = $item['price_origin'];
                        }
                    }
                }

                //更新商品库存和价格
                $this->mallGoods->stock = $totalStock;
                $this->mallGoods->price = $miniPrice;
                $this->mallGoods->price_origin = $miniPriceOrigin;
                $this->mallGoods->save();

                if ($ids) {
                    //清除无用库存配置，加了软删除
                    MallGoodsStock::whereNotIn('id', $ids)->delete();
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->handleResponse(false, '', $e->getMessage());
            }

            return $this->handleResponse($rs);
        }

        $this->setNav();
        //分类规格配置
        $attrs = MallCateAttr::buildForSku($this->mallGoods->cate_id);
        //规格数据
        $specData = MallGoodsStock::where('goods_id', $this->mallGoods->id)->select();
        $form = (new Form)->createElm();
        $element = new CustomComponent('sku');
        $element->field('sku');
        //暂时不开启自定义规格
        //$element->prop('customSpec', true);
        $element->prop('specs', $attrs ?? []);
        $element->prop('defaultProductNo', "P{$this->mallGoods->id}-");
        $element->value($specData->toArray());
        $form->appendCustom($element, 'sku');

        View::assign('form', $form);

        return View::fetch('/mallGoodsSetting/sku');
    }

    /**
     * 图集
     * @throws \Exception
     */
    public function images()
    {
        //规格数据
        $specData = MallGoodsStock::where('goods_id', $this->mallGoods->id)->select();
        if ($this->request->post()) {
            $rs = false;
            foreach ($specData as $specDatum) {
                $image = $this->request->post($specDatum->product_no);
                if (!$image) {
                    continue;
                }
                $specDatum->image = $image;
                $rs = $specDatum->save() || $rs;
            }
            return $this->handleResponse($rs, '保存成功', '保存失败');
        }
        $this->setNav();

        $form = (new Form)->createElm();
        $formStyle = Elm::formStyle();
        $formStyle->labelWidth('200px');
        $formConfig = Elm::config();
        $formConfig->formStyle($formStyle);
        $form->setConfig($formConfig);
        $upload_url = config('thinkAdmin.upload_url');
        $col = Elm::col();
        $col->span(8);
        foreach ($specData as $specDatum) {
            $element = Elm::uploadImage(
                $specDatum->product_no,
                $specDatum->product_no . ': ' . implode(',', $specDatum->spec),
                $upload_url,
                $specDatum->image
            );
            $element->col($col);
            $form->append($element);
        }
        View::assign('form', $form);
        return View::fetch('/mallGoodsSetting/images');
    }

}